import React, { useState, useRef } from 'react';
import styles from '../lyf/LuYin.module.css';
import { CloseOutline, CheckOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';

export default function LuYin() {
  const [isRecording, setIsRecording] = useState(false);
  const [error, setError] = useState(null);
  const [audioBlob, setAudioBlob] = useState(null);
  const mediaRecorderRef = useRef(null);
  const audioChunksRef = useRef([]);
  const navigate = useNavigate()

  // 显示错误提示
  const showError = (errorMessage) => {
    setError(errorMessage);
    setTimeout(() => setError(null), 5000);
  };

  // 开始录音
  const startRecording = async () => {
    try {
      // 请求麦克风权限并设置录音
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mediaRecorder = new MediaRecorder(stream);
      mediaRecorderRef.current = mediaRecorder;
      
      // 设置音频数据收集
      audioChunksRef.current = [];
      mediaRecorder.ondataavailable = (event) => {
        audioChunksRef.current.push(event.data);
      };
      
      mediaRecorder.onstop = () => {
        const blob = new Blob(audioChunksRef.current, { type: 'audio/wav' });
        setAudioBlob(blob);
      };
      
      mediaRecorder.start();
      setIsRecording(true);
      setError(null);

    } catch (err) {
      showError('无法启动录音，请检查麦克风权限');
      setIsRecording(false);
    }
  };

  // 停止录音
  const stopRecording = () => {
    if (mediaRecorderRef.current) {
      mediaRecorderRef.current.stop();
      // 停止所有音轨
      mediaRecorderRef.current.stream.getTracks().forEach(track => track.stop());
    }
    setIsRecording(false);
  };

  // 取消录音
  const handleCancel = () => {
    stopRecording();
    setAudioBlob(null);
  };

  // 确认并发送录音
  const handleConfirm = () => {
    if (!audioBlob) {
      showError('没有可发送的录音内容');
      return;
    }

    // 将录音内容发送到聊天页面
    navigate('/websoket', {
      state: {
        audioBlob: audioBlob,
      }
    });
  };

  return (
    <div className={styles.container}>
      {/* 顶部标题 */}
      <div className={styles.header}>
        <h1 className={styles.title}>说出你心中的任何想法</h1>
        <p className={styles.subtitle}>
          弗洛伊德博士AI会聆听并分析你的声音表情
        </p>
      </div>
      
      {/* 错误提示 */}
      {error && (
        <div className={styles.errorContainer}>
          <div className={styles.errorBox}>
            <div className={styles.errorIcon}>×</div>
            <div className={styles.errorText}>{error}</div>
          </div>
        </div>
      )}
      
      {/* 显示录音状态 */}
      <div className={styles.transcriptContainer}>
        {audioBlob ? (
          <p className={styles.audioReady}>录音已准备就绪</p>
        ) : isRecording ? (
          <p className={styles.recordingStatus}>录音中...</p>
        ) : (
          <p className={styles.placeholder}>点击麦克风开始录音</p>
        )}
      </div>
      
      {/* 主体卡通形象 */}
      <div className={styles.characterContainer}>
        <div className={styles.character}>
          <div className={styles.characterImage}></div>
          <div className={styles.radialLight} style={{
            opacity: isRecording ? 1 : 0.5,
            transition: 'opacity 0.3s ease'
          }}></div>
        </div>
      </div>
      
      {/* 底部控制区域 */}
      <div className={styles.controls}>
        <div className={styles.buttons}>
          <button 
            className={styles.cancelButton}
            onClick={handleCancel}
          >
            <CloseOutline className={styles.icon} />
          </button>
          
          {/* 麦克风按钮 */}
          <div className={styles.micContainer}>
            <div 
              className={`${styles.micCircle} ${isRecording ? styles.recording : ''}`}
              onClick={isRecording ? stopRecording : startRecording}
            >
              <div className={styles.micIcon}></div>
            </div>
          </div>
          
          <button 
            className={styles.confirmButton}
            onClick={handleConfirm}
            disabled={!audioBlob}
          >
            <CheckOutline className={styles.icon} />
          </button>
        </div>
        
        <p className={styles.prompt}>
          {isRecording ? '正在录音...' : audioBlob ? '点击✓发送录音' : '准备好？'}
        </p>
      </div>
    </div>
  );
}